package com.fulihui.wgj.admin.upload;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.*;
import com.fulihui.wgj.admin.config.properties.OSSProperties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import java.io.ByteArrayInputStream;
import java.net.URL;
import java.util.Calendar;
import java.util.Date;
import java.util.Objects;
import java.util.UUID;

/**
 * @author: Levon
 * @version: v 0.1 2018-06-08 11:00
 */
@Component
public class OSSUpload {
    private static final Logger LOG = LoggerFactory.getLogger(OSSUpload.class);

    @Autowired
    private OSSProperties ossProperties;

    private OSSClient client;

    @PostConstruct
    public void init() {
        client = new OSSClient(ossProperties.getEndpoint(), ossProperties.getAccessKeyId(), ossProperties.getSecretAccessKey());

        if (!client.doesBucketExist(ossProperties.getBucket())) {
            //私有读写创建
            //client.createBucket(ossProperties.getBucket());
            //指定权限创建
            CreateBucketRequest createBucketRequest = new CreateBucketRequest(ossProperties.getBucket());
            //设置bucket权限为公共读，默认是私有读写
            createBucketRequest.setCannedACL(CannedAccessControlList.PublicReadWrite);
            // 设置bucket存储类型为低频访问类型，默认是标准类型
            createBucketRequest.setStorageClass(StorageClass.Standard);
            client.createBucket(createBucketRequest);
        }
    }

    public String upload(MultipartFile in) {
        try {
            String fileName = in.getOriginalFilename();
            for (int i = 0; i < 10; i++) {
                String genKey = genKey(fileName);
                if (!client.doesObjectExist(ossProperties.getBucket(), genKey)) {
                    PutObjectResult result = client.putObject(new PutObjectRequest(ossProperties.getBucket(), genKey, new ByteArrayInputStream(in.getBytes())));
                    if (Objects.nonNull(result)) {
                        LOG.info("upload result : {}", result.getETag());
                    }
                    Calendar cal = Calendar.getInstance();
                    cal.add(Calendar.YEAR, 50);
                    Date expiration = cal.getTime();
                    if (client.doesObjectExist(ossProperties.getBucket(), genKey)) {
                        URL url = client.generatePresignedUrl(ossProperties.getBucket(), genKey, expiration);
                        if (Objects.nonNull(url)) {
                            String fileNameSuffix = fileName.substring(fileName.lastIndexOf("."));
                            String urlStr = url.toString().substring(0, url.toString().indexOf(fileNameSuffix) + fileNameSuffix.length());
                            return urlStr;
                        }
                    }
                }
            }
        } catch (Exception e) {
            LOG.error("文件上传错误 ： {}", e);
        }

        return null;
    }

    private String genKey(String fileName) {
        String fileNameSuffix = fileName.substring(fileName.lastIndexOf("."));
        String md5Str = UUID.randomUUID().toString().replaceAll("-", "");
        return ossProperties.getPrefix() + md5Str + fileNameSuffix;
    }

    @PreDestroy
    public void destroy() {
        client.shutdown();
    }
}
